package com.hakim.wfb.customer.service.impl;

import com.alibaba.fastjson.JSON;
import com.hakim.wfb.bean.*;
import com.hakim.wfb.biz.PointOrderBiz;
import com.hakim.wfb.common.enums.*;
import com.hakim.wfb.customer.enums.ErrorCodeEnum;
import com.hakim.wfb.customer.enums.TradePasswordStatusEnum;
import com.hakim.wfb.customer.enums.UserIDAuthStatusEnum;
import com.hakim.wfb.customer.params.trans.ConsumeRecordParameter;
import com.hakim.wfb.customer.params.trans.TransferCreditPointParameter;
import com.hakim.wfb.customer.params.user.*;
import com.hakim.wfb.customer.result.trans.ConsumeRecordView;
import com.hakim.wfb.customer.result.user.*;
import com.hakim.wfb.customer.service.UserService;
import com.hakim.wfb.customer.service.convert.user.UserViewDtv;
import com.hakim.wfb.dao.*;
import com.hakim.wfb.sms.bean.idMsg.IdCheckMsg;
import com.hakim.wfb.sms.service.impl.IdCheckServiceImpl;
import com.hakim.wfb.sms.service.impl.SmsMsgSendServiceImpl;
import com.hkfs.fundamental.api.data.ListResultEx;
import com.hkfs.fundamental.api.data.ObjectResultEx;
import com.hkfs.fundamental.api.data.ResultEx;
import com.hkfs.fundamental.api.params.SessionIdentity;
import com.hkfs.fundamental.common.utils.NumberUtils;
import com.hkfs.fundamental.common.utils.StrUtils;
import com.hkfs.fundamental.config.FundamentalConfigProvider;
import com.hkfs.fundamental.exception.HkfsBizException;
import com.hkfs.fundamental.lock.redis.LockService;
import com.hakim.wfb.common.serial.SerialNoGenerator;
import com.hakim.wfb.common.serial.TreeSerialGenerator;
import com.hakim.wfb.common.serial.UUIDGenerator;
import com.hakim.wfb.common.util.DateUtils;
import com.hakim.wfb.common.util.LockerUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by walkman on 2017/6/30.
 */
@Service("userService")
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserDao userDao;

    @Autowired
    private CreditPointDao creditPointDao;

    @Autowired
    private UserLoginLogDao userLoginLogDao;

    @Autowired
    private PointOrderBiz pointOrderBiz;

    @Autowired
    private ConsumeRecordDao consumeRecordDao;

    @Autowired
    private WithdrawAddrDao withdrawAddrDao;

    @Autowired
    private LockService lockService;

    @Override
    @Transactional
    public ResultEx registerUser(RegisterUserParameter param) {
        ResultEx result = new ResultEx();
        //验证用户名是否已存在
        User userExist = userDao.getUserByUserCode(param.getUserCode());
        if (userExist != null) {
            result.setRetCode(ErrorCodeEnum.USER_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_EXIST_ERROR.getMessage());
            return new ResultEx().makeFailedResult();
        }
        userExist = userDao.getUserByUserPhone(param.getUserPhone());
        if (userExist != null) {
            result.setRetCode(ErrorCodeEnum.MOBILE_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.MOBILE_EXIST_ERROR.getMessage());
            return new ResultEx().makeFailedResult();
        }
        userExist = userDao.getUserByCardNo(param.getUserCardNo());
        if (userExist != null) {
            result.setRetCode(ErrorCodeEnum.CARD_NO_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.CARD_NO_EXIST_ERROR.getMessage());
            return new ResultEx().makeFailedResult();
        }
        Date now = new Date();
        User user = new User();
        String userId = UUIDGenerator.getUUID();
        user.setTid(userId);
        user.setUserCode(param.getUserCode());
        user.setUserPhone(param.getUserPhone());
        user.setUserPwd(param.getUserPassword());
        user.setUserName(param.getUserName());

        user.setUserActStatus(UserActiveTypeEnum.NOTACTIVED.getValue());
        user.setUserInvesting(UserInvestStatusEnum.NOT_INVEST.getValue());
        user.setUserRegTime(now);

        if (StringUtils.isNotBlank(param.getUserCardNo())) {
            user.setUserIdAuth(UserIDAuthStatusEnum.AUTHED.getCode());
        } else {
            user.setUserIdAuth(UserIDAuthStatusEnum.UNAUTHED.getCode());
        }
        user.setUserCardNo(param.getUserCardNo());
        user.setUserTradepwdSet(TradePasswordStatusEnum.SET_NOT.getCode());
        //计算用户组织代码
        if (StringUtils.isBlank(param.getRefer())) {
            //无推荐人
            user.setUserOrg(TreeSerialGenerator.createNextChildSerial(""));
        } else {
            //推荐用户
//            User referUser = userDao.getById(param.getRefer());
            User referUser = userDao.getUserByUserCode(param.getRefer());
            if (referUser == null) {
                //推荐用户不存在
                result.setRetCode(ErrorCodeEnum.INVITE_NOT_EXIST_ERROR.getCode());
                result.setRetMsg(ErrorCodeEnum.INVITE_NOT_EXIST_ERROR.getMessage());
                return result.makeFailedResult();
            } else {
                String nextOrg = "";
                //获取推荐用户的最后直推人
                if (StringUtils.isNotBlank(referUser.getUserLastSubuser())) {
                    User lastSubuser = userDao.getById(referUser.getUserLastSubuser());
                    if (lastSubuser == null) {
                        nextOrg = TreeSerialGenerator.createFirstChildSerial(referUser.getUserOrg());
                    } else {
                        nextOrg = TreeSerialGenerator.createNextChildSerial(lastSubuser.getUserOrg());
                    }
                } else {
                    nextOrg = TreeSerialGenerator.createFirstChildSerial(referUser.getUserOrg());
                }
                user.setUserOrg(nextOrg);
            }
            user.setUserParent(referUser.getTid());
            //更新推荐人的最后直推用户
            User referUserUpdate = new User();
            referUserUpdate.setTid(referUser.getTid());
            referUserUpdate.setUserLastSubuser(userId);
            userDao.update(referUserUpdate);
            //更新推荐用户的等级
        }
        //普通用户
        user.setUserLevel(UserLevelEnum.NORMAL_USER.getValue());
        userDao.add(user);
        //初始化用户积分明细
        CreditPoint creditPoint = new CreditPoint();
        creditPoint.setTid(user.getTid());
        creditPoint.setCpUser(user.getTid());
        creditPoint.setCpActivitPoint(0);
        creditPoint.setCpBenefitLevel(0);
        creditPoint.setCpCapitalPoint(0);
        creditPoint.setCpCustPoint(0);
        creditPoint.setCpDynamicPoint(0);
        creditPoint.setCpElecPoint(0);
        creditPoint.setCpOriginalPoint(0);
        creditPoint.setCpBenefitLevel(0);
        creditPoint.setCpStaticPoint(0);
        creditPoint.setCpAvailableStaticPoint(0);
        creditPoint.setCpReusablePoint(0);
        creditPoint.setCpPerformancePoint(0);
        creditPoint.setCpPerformanceCount(0);
        creditPoint.setCreatedTime(now);
        creditPoint.setUpdatedTime(now);
        creditPoint.setCpTeamPoint(0);
        creditPoint.setCpTeamCount(0);
        creditPointDao.add(creditPoint);
        return result.makeSuccessResult();
    }

    @Override
    @Transactional
    //@ValidateFilters(filterClasses = LoginUserValidateFilter.class)
    public ObjectResultEx<LoginUserView> loginUser(LoginUserParameter parameter) {

        ObjectResultEx<LoginUserView> result = new ObjectResultEx<LoginUserView>();
        User user = userDao.getUserByUserCode(parameter.getUserCode());
        if (user == null) {
            result.setRetCode(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getMessage());
            return result.makeFailedResult();
        }
        if (user.getUserActStatus() != UserActiveTypeEnum.ACTIVED.getValue()) {
            return result.makeFailedResult("用户未激活，请找推荐人激活");
        }
        final Date now = new Date();
        if (!user.getUserPwd().equals(parameter.getPassword())) {
            user.setUserLastLogTime(now);
            userDao.update(user);
            result.setRetCode(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getMessage());
            return result.makeFailedResult();
        }
        user.setUserLastLogTime(now);
        userDao.update(user);
        LoginUserView loginUserView = new LoginUserView();
        loginUserView.setTid(user.getTid());
        loginUserView.setUserCode(user.getUserCode());
        loginUserView.setUserPhone(user.getUserPhone());
        result.setDataObject(loginUserView);
        result.makeSuccessResult();
        if (!result.isSuccess()) {
            return result;
        }
        return result;
    }

    @Override
    public ResultEx loginUserLog(LoginUserLogParameter parameter) {
        ResultEx result = new ResultEx();
        User user = userDao.getUserByUserCode(parameter.getUserCode());
        final Date now = new Date();

        //插入登录日志
        UserLoginLog loginLog = new UserLoginLog();
        loginLog.setTid(UUIDGenerator.getUUID());
        loginLog.setUserId(user.getTid());
        loginLog.setLoginIp(parameter.getClientIp());
        loginLog.setLoginTime(now);
        loginLog.setTerminalType(parameter.getTerminalType().toString());
        if (!user.getUserPwd().equals(parameter.getPassword())) {
            loginLog.setLoginRemark(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getMessage());
            loginLog.setLoginStatus(UserLoginStatus.LOGIN_FAILED.getCode());
            loginLog.setAccessToken("");
            userLoginLogDao.add(loginLog);
            result.setRetCode(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USERNNAME_OR_PASSWORD_ERROR.getMessage());
            return result;
        }
        //设置登录日志信息
        loginLog.setLoginStatus(UserLoginStatus.LOGIN_SUCCESS.getCode());
        loginLog.setAccessToken(parameter.getAccessToken());
        loginLog.setTerminalType(parameter.getTerminalType().toString());
        userLoginLogDao.add(loginLog);
        return result.makeSuccessResult();
    }

    @Override
    public ResultEx logoutUser(LogoutUserParameter param) {

        return new ResultEx().makeSuccessResult();
    }

    /**
     * 通过ref获取用户
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<UserView> queryUserByRef(QueryUserByRefParameter param) {
        ObjectResultEx<UserView> result = new ObjectResultEx<>();
        User user = userDao.getById(param.getRef());
        if (user == null) {
            result.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return result.makeFailedResult();
        }
        UserView userView = new UserView();
        BeanUtils.copyProperties(user, userView);
        result.setDataObject(userView);
        return result.makeSuccessResult();
    }

    /**
     * 用户详细信息
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<UserDetailView> queryUserDetail(GetUserDetailParameter param) {
        ObjectResultEx<UserDetailView> result = new ObjectResultEx<>();
        UserDetailView userView = new UserDetailView();
        result.setDataObject(userView);
        return result.makeSuccessResult();
    }

    /**
     * 绑定手机号码
     *
     * @param param
     * @return
     */
    @Override
    public ResultEx bindMobilephone(BindPhoneParameter param) {

        SessionIdentity sessionIdentity = param.getSessionIdentity();
        String userId = sessionIdentity.getUuid();
        User user = userDao.getById(userId);
        ResultEx result = new ResultEx();
        if (user == null) {
            logger.error("[绑定手机号码]获取用户信息失败 param:{}", JSON.toJSONString(param));
            result.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return result.makeFailedResult();
        }
        if (StringUtils.isNotBlank(param.getMobilePhone()) && !user.getUserPhone().equals(param.getMobilePhone())) {
            throw new HkfsBizException(ErrorCodeEnum.USER_TRADE_PASSWORD_EXIST_ERROR.getCode(), ErrorCodeEnum.USER_TRADE_PASSWORD_EXIST_ERROR.getMessage());
        }
        User userExample = new User();
        userExample.setTid(userId);
        userExample.setUserPhone(param.getMobilePhone());
        userDao.update(userExample);
        return new ResultEx().makeSuccessResult();
    }

    @Override
    public ObjectResultEx<HasTradePasswordView> hasTradePassword(HasTradePasswordParameter param) {
        ObjectResultEx<HasTradePasswordView> result = new ObjectResultEx<HasTradePasswordView>();
        HasTradePasswordView hasTradePasswordView = new HasTradePasswordView();

        User user = userDao.getById(param.getUserId());
        if (StrUtils.notEmpty(user.getUserTradePwd())) {
            hasTradePasswordView.setHasTradePassword(true);
        } else {
            hasTradePasswordView.setHasTradePassword(false);
        }
        result.setDataObject(hasTradePasswordView);
        return result.makeSuccessResult();
    }

    /**
     * 查询用户是否已绑定电子钱包
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<HasBindPacketView> hasBindPacket(HasBindPacketParameter param) {
        ObjectResultEx<HasBindPacketView> result = new ObjectResultEx<HasBindPacketView>();
        HasBindPacketView hasBindPacketView = new HasBindPacketView();

        List<WithdrawAddr> withdrawAddrs = withdrawAddrDao.getWithdrawAddrs(param.getUserId());

        if (withdrawAddrs != null && withdrawAddrs.size() > 0) {
            hasBindPacketView.setHasBindPacket(true);
        } else {
            hasBindPacketView.setHasBindPacket(false);
        }
        result.setDataObject(hasBindPacketView);
        return result.makeSuccessResult();
    }

    /**
     * 查询用户是否已绑定手机号码
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<HasBindPhoneView> hasBindPhone(HasBindPhoneParameter param) {
        ObjectResultEx<HasBindPhoneView> result = new ObjectResultEx<HasBindPhoneView>();
        HasBindPhoneView hasBindPhoneView = new HasBindPhoneView();

        User user = userDao.getById(param.getSessionIdentity().getUuid());
        if (StrUtils.notEmpty(user.getUserPhone())) {
            hasBindPhoneView.setHasBindPhone(true);
        } else {
            hasBindPhoneView.setHasBindPhone(false);
        }
        result.setDataObject(hasBindPhoneView);
        return result.makeSuccessResult();
    }

    @Override
    public ObjectResultEx<UserInviteContentView> getInviteContent(GetInviteContentParameter param) {
//        String title = FundamentalConfigProvider.getString("duc.invite.title");
//        String content = FundamentalConfigProvider.getString("duc.invite.content");
//        Long userId = param.getSessionIdentity().getUserId();
        ObjectResultEx<UserInviteContentView> result = new ObjectResultEx<UserInviteContentView>();
        User user = userDao.getById(param.getUserId());
//        Object[] fmtargs = {user.getTid()};
        String inviteUrl = FundamentalConfigProvider.getString("wfb.invite.url");
        UserInviteContentView invite = new UserInviteContentView();
//        invite.setInviteUrl(MessageFormat.format(inviteUrl, fmtargs));
        invite.setInviteUrl(inviteUrl.trim().replaceAll("\r|\n", "") + "rec=" + user.getUserCode());
        result.setDataObject(invite);
        return result.makeSuccessResult();
    }

    @Override
    public ObjectResultEx<UserDetailView> getUserDetail(String userid) {

        ObjectResultEx<UserDetailView> result = new ObjectResultEx<>();
        UserDetailView userDetailView = userDao.getUserDetail(userid);
        if (userDetailView == null) {
            result.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            result.makeFailedResult();
        }
        result.setDataObject(userDetailView);
        return result.makeSuccessResult();
    }

    public UserDetailView getUserByTid(String userid) {
        return userDao.getUserByTid(userid);
    }

    @Override
//    @ValidateFilters(filterClasses = {CurrentUserPhoneValidateFilter.class, UserValidateFilter.class})
    public ResultEx forgetTradePassword(ForgetTradePasswordParameter param) {
        ResultEx resultEx = new ResultEx();
        Date now = new Date();
        // 1.校验短信验证码是否正确
//        String sessionVerfiyKey = SessionKeys.VERIFY_CODE_PREFIX + param.getMobilePhone() + "." + VerifyCodeType.FORGET_TRADE_PASSWORD.getCode();
//        SessionVerifyCode sessionVerifyCode = SessionVerifyCode.fromStringInfo(RedisConnector.get(sessionVerfiyKey));
//        if (sessionVerifyCode != null && !sessionVerifyCode.getVerifyCode().equals(param.getVerifyCode())) {
//            throw new HkfsBizException(ErrorCodeEnum.VERIFYCODE_ERROR.getCode(), ErrorCodeEnum.VERIFYCODE_ERROR.getMessage());
//        }
//        Long userId = param.getSessionIdentity().getUserId();
//        UpdateUserParameter updateUserParameter = new UpdateUserParameter();
//        updateUserParameter.setId(userId);
//        updateUserParameter.setTradePassword(param.getNewTradePassword());
//        userService.updateUser(updateUserParameter);
//
//        UpdateTradePasswordStatusParameter updateTradePasswordStatusParameter = new UpdateTradePasswordStatusParameter();
//        updateTradePasswordStatusParameter.setTradePasswordStatus(TradePasswordStatus.SET.getCode());
//        updateTradePasswordStatusParameter.setUserId(userId);
//        ObjectResultEx<Integer> updateTradeObj = this.userInfoService.updateTradePasswordStatus(updateTradePasswordStatusParameter);
//        if (updateTradeObj.isFailed()) {
//            logger.info("更新交易密码状态失败 param:{}", JSON.toJSONString(updateTradePasswordStatusParameter));
//            return resultEx.makeFailedResult();
//        }
//        RedisConnector.del(sessionVerfiyKey);
        //微信模版消息——密码修改
//        Map<String, Object> dataMap = new HashMap<>();
//        String type = WeixinPasswordType.FIND_PAY_PASSWORD.getBundleKey();
//        dataMap.put("first", "尊敬的用户您好，您已成功" + type + "。");
//        dataMap.put("keyword1", param.getSessionIdentity().getPhone());
//        dataMap.put("keyword2", type);
//        dataMap.put("keyword3", DateHelper.formatDate(now, DateHelper.YYYY_MM_DD_HH_MM_SS));
//        dataMap.put("remark", "如非本人操作，请联系鼎有财客服热线：400-0077-707");
//        GetUserDetailParameter getUserDetailParameter = new GetUserDetailParameter();
//        getUserDetailParameter.setId(userId);
//        ObjectResultEx<UserDetailView> userDetail = userService.getUserDetail(getUserDetailParameter);
//        UserDetailView userDetailView = userDetail.getDataObject();
//        weixinPushService.sendTemplateMsg(weixinPushService.getAccessToken(), userDetailView.getUserView().getWeixinAccount(), ConfigValues.getTemplateId("duc.weixin.templateId.password"),
//                dataMap, "default");
        return resultEx.makeSuccessResult();
    }

    /**
     * 设置交易密码
     *
     * @param param
     * @return
     */
    @Override
    public ResultEx setTradePassword(SetTradePasswordParameter param) {
        ResultEx result = new ResultEx();
        String userId = param.getUserId();
        User user = userDao.getById(userId);
        if (user == null) {
            logger.error("[设置交易密码]获取用户信息失败 param:{}", JSON.toJSONString(param));
            return new ResultEx().makeFailedResult();
        }
        if (TradePasswordStatusEnum.SET.getCode().equals(user.getUserTradepwdSet())) {
            result.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_EXIST_ERROR.getMessage());
            return result.makeFailedResult();
        }
        if (!param.getConfirmTradePwd().equals(param.getTradePassword())) {
            result.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getMessage());
            return result.makeFailedResult();
        }
        User userExample = new User();
        userExample.setTid(userId);
        userExample.setUserTradepwdSet(TradePasswordStatusEnum.SET.getCode());
        userExample.setUserTradePwd(param.getTradePassword());
        userDao.update(userExample);
        return result.makeSuccessResult();
    }

    /**
     * 修改交易密码
     *
     * @param param
     * @return
     */
    @Override
//    @ValidateFilters(filterClasses = CheckUserExistValidateFilter.class)
    public ResultEx modifyTradePassword(ModifyTradePasswordParameter param) {
        ResultEx result = new ResultEx();
        String userId = param.getUserId();
        User user = userDao.getById(userId);
        if (user != null) {

            if (TradePasswordStatusEnum.SET_NOT.getCode().equals(user.getUserTradepwdSet())) {
                result.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_SET_NO_ERROR.getCode());
                result.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_SET_NO_ERROR.getMessage());
                return result.makeFailedResult();
            }
            if (!user.getUserTradePwd().equals(param.getOldTradePassword())) {
                result.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_ERROR.getCode());
                result.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_ERROR.getMessage());
                return result.makeFailedResult();
            }
            if (!param.getConfirmTradePwd().equals(param.getTradePassword())) {
                result.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getCode());
                result.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getMessage());
                return result.makeFailedResult();
            }
            User userExample = new User();
            userExample.setTid(user.getTid());
            userExample.setUserTradePwd(param.getTradePassword());
            userExample.setUserTradepwdSet(TradePasswordStatusEnum.SET.getCode());
            userDao.update(userExample);
        }
        return result.makeSuccessResult();
    }

    @Override
//    @ValidateFilters(filterClasses = {CheckForgetLoginPassVerifyCodeFilter.class, CheckUserPhoneValidateFilter.class})
    public ResultEx forgetLoginPassword(ForgetLoginPasswordParameter param) {
        ResultEx result = new ResultEx();
        User user = userDao.getUserByUserCode(param.getUserCode());
        if (user != null) {
            User userExample = new User();
            userExample.setTid(user.getTid());
            userExample.setUserPwd(param.getNewPassword());
            userDao.update(user);
        }
        return result.makeSuccessResult();
    }

    @Override
//    @ValidateFilters(filterClasses = ModifyLoginPassValidateFilter.class)
    public ResultEx modifyLoginPassword(ModifyLoginPasswordParameter param) {

        ResultEx resultEx = new ResultEx();
        User user = userDao.getById(param.getUserId());
        if (user != null) {
            if (!user.getUserPwd().equals(param.getOldPassword())) {
                resultEx.setRetCode(ErrorCodeEnum.USER_PASSWORD_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_PASSWORD_ERROR.getMessage());
                return resultEx;
            }
            if (!param.getNewPassword().equals(param.getNewConfirmPassword())) {
                resultEx.setRetCode(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_TRADE_PASSWORD_MISMATCH_ERROR.getMessage());
                return resultEx;
            }
            User userExample = new User();
            userExample.setTid(user.getTid());
            userExample.setUserPwd(param.getNewPassword());
            userDao.update(userExample);
        } else {
            resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return resultEx;
        }
        return resultEx.makeSuccessResult();
    }

    @Override
    public ObjectResultEx<UserView> queryUserByUserCode(QueryUserParameter param) {

        ObjectResultEx<UserView> resultEx = new ObjectResultEx<>();
        User user = userDao.getUserByUserCode(param.getUserCode());
        if (user == null) {
            return resultEx.makeResult(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode(), ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
        }
        UserView userView = UserViewDtv.convert(user);
        resultEx.setDataObject(userView);
        return resultEx.makeSuccessResult();
    }

    /**
     * 登录名查询用户是否存在
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<UserView> queryUserByUserPhone(QueryUserParameter param) {

        ObjectResultEx<UserView> resultEx = new ObjectResultEx<>();
        User user = userDao.getUserByUserPhone(param.getUserMobile());
        if (user == null) {
            return resultEx.makeResult(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode(), ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
        }
        UserView userView = UserViewDtv.convert(user);
        resultEx.setDataObject(userView);
        return resultEx.makeSuccessResult();
    }

    /**
     * 登录名查询用户是否存在
     *
     * @param param
     * @return
     */
    @Override
    public ObjectResultEx<UserView> queryUserByCardNo(QueryUserParameter param) {
        ObjectResultEx<UserView> resultEx = new ObjectResultEx<>();
        User user = userDao.getUserByCardNo(param.getCardNo());
        if (user == null) {
            return resultEx.makeResult(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode(), ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
        }
        UserView userView = UserViewDtv.convert(user);
        resultEx.setDataObject(userView);
        return resultEx.makeSuccessResult();
    }

    @Override
    public ObjectResultEx<UserDetailView> getUserDetail(GetUserDetailParameter param) {

//        UserDetailView userDetailView = userDao.getUserDetail(param.getUuid());

//        if (userDetailView == null) {
//            return result.makeFailedResult();
//        }
//        result.setDataObject(userDetailView);
        ObjectResultEx<UserDetailView> result = new ObjectResultEx<>();
        User user = userDao.getById(param.getUuid());
        if (user == null) {
            result.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
            return result.makeFailedResult();
        }
        CreditPoint creditPoint = creditPointDao.getById(param.getUuid());
        if (creditPoint == null) {

            result.setRetCode(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getCode());
            result.setRetMsg(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getMessage());
            return result.makeFailedResult();
        }
        UserDetailView userDetailView = new UserDetailView();
        userDetailView.setTid(user.getTid());
        userDetailView.setUserCode(user.getUserCode());
        userDetailView.setUserName(user.getUserName());
        userDetailView.setUserOrg(user.getUserOrg());
        userDetailView.setUserLevel(user.getUserLevel());
        userDetailView.setUserActStatus(user.getUserActStatus());
        userDetailView.setUserIdAuth(user.getUserIdAuth());
        userDetailView.setUserPacketBound(user.getUserPacketBound());
        userDetailView.setUserTradepwdSet(user.getUserTradepwdSet());
        userDetailView.setCpCustPoint(creditPoint.getCpCustPoint());
        userDetailView.setCpActivitPoint(creditPoint.getCpActivitPoint());
        userDetailView.setCpElecPoint(creditPoint.getCpElecPoint());
        userDetailView.setCpOriginalPoint(creditPoint.getCpOriginalPoint());
        userDetailView.setCpRepeatPoint(creditPoint.getCpRepeatPoint());
        userDetailView.setCpDynamicPoint(creditPoint.getCpDynamicPoint());
        userDetailView.setCpStaticPoint(creditPoint.getCpStaticPoint());
        userDetailView.setCpAvailableStaticPoint(creditPoint.getCpAvailableStaticPoint());
        userDetailView.setCpBenefitLevel(creditPoint.getCpBenefitLevel());
        userDetailView.setCpCapitalPoint(creditPoint.getCpCapitalPoint());
        userDetailView.setCpReusablePoint(creditPoint.getCpReusablePoint());
        userDetailView.setCpInRepeatPoint(creditPoint.getCpTeamPoint());
        userDetailView.setCpPerformancePoint(creditPoint.getCpPerformancePoint());
        userDetailView.setCpPerformanceCount(creditPoint.getCpPerformanceCount());
        userDetailView.setCpTeamPoint(creditPoint.getCpTeamPoint());
        userDetailView.setCpTeamCount(creditPoint.getCpTeamCount());
        result.setDataObject(userDetailView);
        return result.makeSuccessResult();
    }

    /**
     * 激活团队成员
     *
     * @param userid
     * @param uuid
     * @return
     */
    @Override
    @Transactional
    public ResultEx activateMember(String userid, String uuid) {

        ResultEx resultEx = new ResultEx();
        Integer lockId = NumberUtils.random(0, 1000000);
        Boolean isLockSuccess = false;
        try {
            isLockSuccess = lockService.lock(LockerUtils.UNIQUE_LOCK_Key, LockService.DEFAULT_TRY_LOCK_MILLIS,
                    LockService.DEFAULT_AUTO_UNLOCK_MILLIS, lockId);
            if (!isLockSuccess) {
                return resultEx.makeFailedResult("锁定出错！");
            }

            //扣除用户激活积分
            User fromUser = userDao.getById(uuid);
            CreditPoint userCp = creditPointDao.getById(uuid);
            double actPoint = userCp.getCpActivitPoint();
            if (actPoint < 100) {
                return resultEx.makeFailedResult("用户激活积分不足");
            }
            userCp.setCpActivitPoint(actPoint - 100);
            creditPointDao.update(userCp);
            User user = userDao.getById(userid);
            if (user == null) {
                resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            if (user.getUserActStatus().equals(UserActiveTypeEnum.ACTIVED.getValue())) {
                resultEx.setRetCode(ErrorCodeEnum.USER_ALREADY_ACTIVATED_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_ALREADY_ACTIVATED_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            // 更新被激活用户状态
            User userActive = new User();
            userActive = userDao.getById(userid);

            userActive.setTid(userid);
            userActive.setUserActTime(new Date());
            userActive.setUserActStatus(UserActiveTypeEnum.ACTIVED.getValue());
            int cou = userDao.activateUser(userActive);

            // 积分流转记录（当前用户激活积分给系统，系统收到当前用户激活积分）
            //系统为正数
            String orderno = SerialNoGenerator.getActivateOrderNo(user.getUserPhone());
            PointOrder custPointOrder = new PointOrder();
            custPointOrder.setTid(UUIDGenerator.getUUID());
            custPointOrder.setPoAmount(0);
            custPointOrder.setPoCreateDate(DateUtils.getNow());
            custPointOrder.setPoDescription("用户code:【" + userActive.getUserCode() + "】被用户【" + fromUser.getUserCode() + "】激活,系统收到 " + fromUser.getUserCode() + " 激活积分：" + 100);
            custPointOrder.setPoFromUser(uuid);
            custPointOrder.setPoOrderno(orderno);
            custPointOrder.setPoPointType(PointTypeEnum.ACTIVITY_POINT.getValue());
            custPointOrder.setPoToUser("0");
            custPointOrder.setPoTransPoint(100);
            custPointOrder.setPoType(TransTypeEnum.ACTIVITY.getValue());
            pointOrderBiz.add(custPointOrder);

            //用户为负数
            PointOrder reverseCustPointOrder = new PointOrder();
            reverseCustPointOrder.setTid(UUIDGenerator.getUUID());
            reverseCustPointOrder.setPoAmount(actPoint - 100);
            reverseCustPointOrder.setPoCreateDate(DateUtils.getNow());
            reverseCustPointOrder.setPoDescription("用户" + fromUser.getUserCode() + "激活用户code:【" + userActive.getUserCode() + "】, " + fromUser.getUserCode() + " 支出激活积分：" + -100);
            reverseCustPointOrder.setPoFromUser(uuid);
            reverseCustPointOrder.setPoOrderno(orderno);
            reverseCustPointOrder.setPoPointType(PointTypeEnum.ACTIVITY_POINT.getValue());
            reverseCustPointOrder.setPoToUser("0");
            reverseCustPointOrder.setPoTransPoint(-100);
            reverseCustPointOrder.setPoType(TransTypeEnum.ACTIVITY.getValue());
            pointOrderBiz.add(reverseCustPointOrder);

            return resultEx.makeSuccessResult();

        } catch (Exception e) {
            return resultEx.makeFailedResult("操作失败" + e);
        } finally {
            if (isLockSuccess) {
                lockService.unlock(LockerUtils.UNIQUE_LOCK_Key, lockId);
            }
        }
    }

    /**
     * 系统管理员激活初代用户
     *
     * @param parameter
     * @return
     */
    @Override
    @Transactional
    public ResultEx activateCustomer(ActivateCustomerParameter parameter) {

        ResultEx resultEx = new ResultEx();

        Integer lockId = NumberUtils.random(0, 1000000);
        Boolean isLockSuccess = false;
        try {
            isLockSuccess = lockService.lock(LockerUtils.UNIQUE_LOCK_Key, LockService.DEFAULT_TRY_LOCK_MILLIS,
                    LockService.DEFAULT_AUTO_UNLOCK_MILLIS, lockId);
            if (!isLockSuccess) {
                return resultEx.makeFailedResult("锁定出错！");
            }
            User fromUser = userDao.getById(parameter.getUuid()); // 管理员
            User toUser = userDao.getById(parameter.getUserId());  //
            // 更新被激活用户状态
            User user = userDao.getById(parameter.getUserId());
            if (user == null) {
                resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            if (user.getUserActStatus().equals(UserActiveTypeEnum.ACTIVED.getValue())) {
                resultEx.setRetCode(ErrorCodeEnum.USER_ALREADY_ACTIVATED_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_ALREADY_ACTIVATED_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }

            User userUpdate = new User();
            userUpdate.setTid(parameter.getUserId());
            userUpdate.setUserActTime(new Date());
            userUpdate.setUserActStatus(UserActiveTypeEnum.ACTIVED.getValue());
            int cou = userDao.activateUser(userUpdate);

            // 积分流转记录（当前用户激活积分给系统，系统收到当前用户激活积分）
            //系统为正数
            String orderno = SerialNoGenerator.getActivateOrderNo(userUpdate.getUserPhone());
            PointOrder custPointOrder = new PointOrder();
            custPointOrder.setTid(UUIDGenerator.getUUID());
            custPointOrder.setPoAmount(0);
            custPointOrder.setPoCreateDate(DateUtils.getNow());
            custPointOrder.setPoDescription("用户code:【" + toUser.getUserCode() + "】被管理员【" + fromUser.getUserCode() + "】激活,系统收到系统管理员 " + fromUser.getUserCode() + " 激活积分：" + 100);
            custPointOrder.setPoFromUser(parameter.getUuid());
            custPointOrder.setPoOrderno(orderno);
            custPointOrder.setPoPointType(PointTypeEnum.ACTIVITY_POINT.getValue());
            custPointOrder.setPoToUser("0");
            custPointOrder.setPoTransPoint(100);
            custPointOrder.setPoType(TransTypeEnum.ACTIVITY.getValue());
            pointOrderBiz.add(custPointOrder);

            //用户为负数
            PointOrder reverseCustPointOrder = new PointOrder();
            reverseCustPointOrder.setTid(UUIDGenerator.getUUID());
            reverseCustPointOrder.setPoCreateDate(DateUtils.getNow());
            reverseCustPointOrder.setPoDescription("系统管理员" + fromUser.getUserCode() + "激活用户code:【" + toUser.getUserCode() + "】, 系统管理员" + fromUser.getUserCode() + " 支出激活积分：" + -100);
            reverseCustPointOrder.setPoFromUser("0");
            reverseCustPointOrder.setPoOrderno(orderno);
            reverseCustPointOrder.setPoPointType(PointTypeEnum.ACTIVITY_POINT.getValue());
            reverseCustPointOrder.setPoToUser(toUser.getUserCode());
            reverseCustPointOrder.setPoTransPoint(-100);
            reverseCustPointOrder.setPoType(TransTypeEnum.ACTIVITY.getValue());
            pointOrderBiz.add(reverseCustPointOrder);

            return resultEx.makeSuccessResult();

        } catch (Exception e) {
            resultEx = new ResultEx();
            return resultEx.makeFailedResult("操作失败");
        } finally {
            if (isLockSuccess) {
                lockService.unlock(LockerUtils.UNIQUE_LOCK_Key, lockId);
            }
        }
    }

    @Override
    @Transactional
    public ResultEx sysTransferPoint(TransferCreditPointParameter parameter) {

        ResultEx resultEx = new ResultEx();

        Integer lockId = NumberUtils.random(0, 1000000);
        Boolean isLockSuccess = false;
        try {

            isLockSuccess = lockService.lock(LockerUtils.UNIQUE_LOCK_Key, LockService.DEFAULT_TRY_LOCK_MILLIS,
                    LockService.DEFAULT_AUTO_UNLOCK_MILLIS, lockId);
            if (!isLockSuccess) {
                return resultEx.makeFailedResult("锁定出错！");
            }
            // 获取收取积分的用户
            User recUser = userDao.getById(parameter.getCpUser());
            if (recUser == null) {
                resultEx.setRetCode(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_NOT_EXIST_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            CreditPoint creditPoint = creditPointDao.getById(recUser.getTid());
            if (creditPoint == null) {

                resultEx.setRetCode(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.USER_CREDIT_POINT_NOT_EXIST_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            if (parameter.getCpPointAmount() <= 0.0) {
                resultEx.setRetCode(ErrorCodeEnum.CREDIT_POINT_INVALID_ERROR.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.CREDIT_POINT_INVALID_ERROR.getMessage());
                return resultEx.makeFailedResult();
            }
            String desc = "";
            String desc2 = "";
            double tranPoints = 0;
            int pt = 0;
            //消费积分
            if (parameter.getPointType() == PointTypeEnum.CUST_POINT.getValue()) {
                creditPoint.setCpCustPoint(creditPoint.getCpCustPoint() + parameter.getCpPointAmount());
                desc = "管理员[" + parameter.getSysUuid() + "]划拨" + -parameter.getCpPointAmount() + "消费积分给用户【" + recUser.getUserCode() + "】";
                desc2 = "用户【" + recUser.getUserCode() + "】收到管理员【" + parameter.getSysUuid() + "】划拨的" + parameter.getCpPointAmount() + "消费积分";

                tranPoints = parameter.getCpPointAmount();

            } else if (parameter.getPointType() == PointTypeEnum.ACTIVITY_POINT.getValue()) {
                //激活积分
                creditPoint.setCpActivitPoint(creditPoint.getCpActivitPoint() + parameter.getCpPointAmount());
                desc = "管理员[" + parameter.getSysUuid() + "]划拨" + -parameter.getCpPointAmount() + "激活积分给用户【" + recUser.getUserCode() + "】";
                desc2 = "用户【" + recUser.getUserCode() + "】收到管理员【" + parameter.getSysUuid() + "】划拨的" + parameter.getCpPointAmount() + "激活积分";
                tranPoints = parameter.getCpPointAmount();
            } else if (parameter.getPointType() == PointTypeEnum.ELEC_POINT.getValue()) {
                //电子积分
                creditPoint.setCpElecPoint(creditPoint.getCpElecPoint() + parameter.getCpPointAmount());
                desc = "管理员[" + parameter.getSysUuid() + "]划拨" + -parameter.getCpPointAmount() + "电子积分给用户【" + recUser.getUserCode() + "】";
                desc2 = "用户【" + recUser.getUserCode() + "】收到管理员【" + parameter.getSysUuid() + "】划拨的" + parameter.getCpPointAmount() + "电子积分";
                tranPoints = parameter.getCpPointAmount();
            } else {
                resultEx.setRetCode(ErrorCodeEnum.CREDIT_POINT_TYPE_NOT_SUPPORT_TRANSFER.getCode());
                resultEx.setRetMsg(ErrorCodeEnum.CREDIT_POINT_TYPE_NOT_SUPPORT_TRANSFER.getMessage());
                return resultEx.makeFailedResult();
            }

            int cou = creditPointDao.update(creditPoint);

            // 积分流转记录（当前用户激活积分给系统，系统收到当前用户激活积分）
            //系统为负数
            String orderno = SerialNoGenerator.getActivateOrderNo(recUser.getUserPhone());
            PointOrder custPointOrder = new PointOrder();
            custPointOrder.setTid(UUIDGenerator.getUUID());
            custPointOrder.setPoAmount(0);
            custPointOrder.setPoCreateDate(DateUtils.getNow());
            custPointOrder.setPoDescription(desc);
            custPointOrder.setPoFromUser(parameter.getSysUuid());
            custPointOrder.setPoOrderno(orderno);
            custPointOrder.setPoPointType(parameter.getPointType());
            custPointOrder.setPoToUser(recUser.getTid());
            custPointOrder.setPoTransPoint(-tranPoints);
            custPointOrder.setPoType(TransTypeEnum.SYSTRANS.getValue());
            pointOrderBiz.add(custPointOrder);

            //用户为负数
            PointOrder reverseCustPointOrder = new PointOrder();
            reverseCustPointOrder.setTid(UUIDGenerator.getUUID());
            reverseCustPointOrder.setPoCreateDate(DateUtils.getNow());
            reverseCustPointOrder.setPoDescription(desc);
            reverseCustPointOrder.setPoFromUser(parameter.getSysUuid());
            reverseCustPointOrder.setPoOrderno(orderno);
            reverseCustPointOrder.setPoPointType(parameter.getPointType());
            reverseCustPointOrder.setPoToUser(recUser.getTid());
            reverseCustPointOrder.setPoTransPoint(tranPoints);
            reverseCustPointOrder.setPoType(TransTypeEnum.SYSTRANS.getValue());
            pointOrderBiz.add(reverseCustPointOrder);

            return resultEx.makeSuccessResult();

        } catch (Exception e) {
            return resultEx.makeFailedResult("操作失败");
        } finally {
            if (isLockSuccess) {
                lockService.unlock(LockerUtils.UNIQUE_LOCK_Key, lockId);
            }
        }
    }

    @Override
    public ListResultEx<ConsumeRecordView> getAllInvest(ConsumeRecordParameter param) {
        ListResultEx<ConsumeRecordView> lrs = new ListResultEx<ConsumeRecordView>();
        try {
            List<ConsumeRecordView> relist = consumeRecordDao.getAllInvest(param);
            lrs.setTotalCount(relist.size());
            lrs.setDataList(relist);
            return lrs.makeSuccessResult();
        } catch (Exception e) {
            return lrs.makeFailedResult("查询失败" + e);
        }
    }

    @Override
    public ListResultEx<UserView> queryUserList(QueryCustomerWebPageParameter parameter) {
        ListResultEx<UserView> listResultEx = new ListResultEx<UserView>();
        try {

            List<UserView> userViewList = userDao.queryUserList(parameter);
            Integer count = userDao.queryUserCount(parameter);
            listResultEx.setTotalCount(count);
            listResultEx.setDataList(userViewList);
            return listResultEx.makeSuccessResult();
        } catch (Exception e) {
            return listResultEx.makeFailedResult("查询失败" + e);
        }
    }

    @Override
    public ResultEx validMsg(String tels, String msg) {
        ResultEx re = new ResultEx();
        boolean res = new SmsMsgSendServiceImpl().sendMsg(tels, msg);
        if (res == true)
            return re.makeResult(1, msg);
        else return re.makeFailedResult("发送失败");
    }

    @Override
    public ResultEx checkIdentity(String name, String identity) {
        return IdCheckServiceImpl.checkIdentity(name, identity);
    }

    public static void main(String[] args) {
        IdCheckMsg msg = new IdCheckMsg();
        msg.setYwlx("check identity");
        msg.setSessionId("");
        msg.setGmsfhm("130432198706110315");
        msg.setXm("陈磊");
        msg.setFsd("北京");
        msg.setAccount("sin7");
        msg.setXp("");
        msg.setAction("qsfz");
        msg.setCid("sin718600992571");
        System.out.println("--------------checkIdentity(\"陈磊\",\"130432198706110315\")---------------");
        System.out.println(IdCheckServiceImpl.checkIdentity("陈磊", "130432198706110315"));
        System.out.println("--------------checkIdentity(\"陈磊a\",\"130432198706110315\")---------------");
        System.out.println(IdCheckServiceImpl.checkIdentity("陈磊a", "130432198706110315"));
        System.out.println("----------------checkIdentity(\"陈 磊\",\"130432198706110315\")-------------");
        System.out.println(IdCheckServiceImpl.checkIdentity("陈 磊", "130432198706110315"));
        System.out.println("------------checkIdentity(\"陈磊\",\"130432198706110315X\")-----------------");
        System.out.println(IdCheckServiceImpl.checkIdentity("陈磊", "130432198706110315X"));
        System.out.println("---------------checkIdentity(\"陈磊\",\"130432198706110X\")--------------");
        System.out.println(IdCheckServiceImpl.checkIdentity("陈磊", "130432198706110X"));
    }

}

